#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <sys/wait.h>
#include <pthread.h>
#include <functional>
#include <memory>
#include "InetAddr.hpp"
#include "Log.hpp"

using namespace std;

// 模板方法模式
enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR
};

namespace yss
{
    class Socket;
    const static int backlog = 8;
    using socket_sptr = shared_ptr<Socket>;

    class Socket
    {
    public:
        virtual void CreateSocketOrdie() = 0;
        virtual void BindSocketOrdie(InetAddr &addr) = 0;
        virtual void ListenSocketOrdie() = 0;
        virtual socket_sptr Accepter(InetAddr *addr) = 0;
        virtual bool Connectcor(InetAddr &addr) = 0;
        virtual int Sockfd() = 0;
        virtual int Recv(string *out) = 0;
        virtual int Send(const string &in) = 0;

    public:
        void BuildListenSocket(InetAddr &addr)
        {
            CreateSocketOrdie();
            BindSocketOrdie(addr);
            ListenSocketOrdie();
        }
        bool BuildClientSocket(InetAddr &addr)
        {
            CreateSocketOrdie();
            Connectcor(addr);
            return true;
        }
        // void BuildUdpSocket()
        // {
        //     CreateSocketOrdie();
        //     BindSocketOrdie();
        // }
    };
    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int fd = -1) : _sockfd(fd)
        {
        }
        void CreateSocketOrdie() override
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket error");
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "socket create success, sockfd: %d", _sockfd);
        }
        void BindSocketOrdie(InetAddr &addr) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(addr.Port());
            local.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind error");
                exit(BIND_ERROR);
            }
            LOG(INFO, "bind create success, sockfd: %d", _sockfd);
        }
        void ListenSocketOrdie() override
        {
            int n = listen(_sockfd, backlog);
            if (n < 0)
            {
                LOG(FATAL, "listen error");
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "listen create success, sockfd: %d", _sockfd);
        }
        socket_sptr Accepter(InetAddr *addr) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_sockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "listen error");
                return nullptr;
            }
            *addr = peer;
            socket_sptr sock = make_shared<TcpSocket>(sockfd);
            return sock;
        }
        bool Connectcor(InetAddr &addr)
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(addr.Port());
            server.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            // 发起连接
            int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                cout << "connect error" << endl;
                return false;
            }
            return true;
        }
        int Sockfd() override
        {
            return _sockfd;
        }

        int Recv(string *out) override
        {
            char inbuffer[1024];
            ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer)-1, 0);
            if (n > 0) // 读成功
            {
                inbuffer[n] = 0;
                *out += inbuffer;
            }
            return n;
        }

        int Send(const string &in) override
        {
            int n = ::send(_sockfd, in.c_str(), in.size(), 0);
            return n;
        }

    private:
        int _sockfd;
    };
}